//
//  MultiPageContentRefresher.swift
//  EVOP
//
//  Created by LC_WJH on 2017/8/15.
//  Copyright © 2017年 gmc. All rights reserved.
//

import Foundation
import MJRefresh


//专门用于多页读取内容的辅助类
public class MultiPageContentRefresher:NSObject {
    
    
    
    public static let PAGE_START = 1;
    
    var currentPage:Int = PAGE_START;
    var fetchNum = 10 ;
    
    
    public typealias RefreshToPage = (Int/*page*/,Int/*fetchNum*/)->URLSessionDataTask?;
    
    var cb:RefreshToPage?;
    weak var target:UITableView?;
    
    //带辅助网络连接管理
    public weak var lastNetWorkTask: URLSessionDataTask?;

    
    //开始对table的拉取进行管理
    public func startManagerForMJTable(table:UITableView,oncall:@escaping RefreshToPage,withPageSize:Int)->Void{
        
        target = table;
        cb = oncall;
        
        if( withPageSize > 1 ){
            fetchNum = withPageSize;
        }
        
        if target != nil {
            
            weak var wSelf = self
            
            target!.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
                if wSelf != nil {
                    
                    wSelf!.currentPage = MultiPageContentRefresher.PAGE_START;
                    wSelf!.lastNetWorkTask?.cancel();
                    wSelf!.lastNetWorkTask = wSelf!.cb?(MultiPageContentRefresher.PAGE_START,wSelf!.fetchNum);
                    
                }
            });
            target!.mj_footer = MJRefreshBackNormalFooter.init(refreshingBlock: {
                if wSelf != nil {
                    
                    wSelf!.currentPage += 1;
                    wSelf!.lastNetWorkTask?.cancel();
                    wSelf!.lastNetWorkTask = wSelf!.cb?(wSelf!.currentPage,wSelf!.fetchNum);
                    
                }
            });

            
            
        }
        
    }
    
    
    //在读取完毕后调用这个函数,重新设置table的显示状态.
    public func callAfterLoadFinished(fetchedNum:Int)->Void{
        
        //如果读取出错,输入 -1 ,否则把实际获取到的返回数量传入即可
        
        
         if target != nil {
            
            target!.mj_header?.endRefreshing();
            
            if fetchedNum <  fetchNum {
                target!.mj_footer?.endRefreshingWithNoMoreData();
            }else{
                target!.mj_footer?.endRefreshing();
            }
        }
        
    }
    
    
    
    
    
}
